package com.terren.spider.run.basic;


import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.terren.spider.db.service.ArticleSearchService;
import com.terren.spider.db.service.SpiderTaskService;
import com.terren.spider.entity.biz.ArticleSearch;
import com.terren.spider.entity.core.Entry;
import com.terren.spider.entity.core.SpiderTask;
import com.terren.spider.run.basic.BasicSpiderRunner;
import com.terren.spider.util.common.CommonUtil;
import com.terren.spider.util.common.DateUtil;
import com.terren.spider.util.common.StringUtil;

public abstract class BasicSpiderArticleSearchRunner extends BasicSpiderRunner<ArticleSearch>{

	protected SpiderTaskService spiderTaskService;// 扒取任务service
	protected ArticleSearchService articleSearchService;// 
	protected SpiderTask tasks;//taskid 状态： -1抓取失败    0 等待抓取   1抓取内容完成（任务完成）  2抓取链接完成（任务未完成）    9 抓取‘链接’任务正在进行  10 抓取‘内容’任务正在进行

	protected final static int RETRY_TIMES = 3;//失败重试次数

	
	public BasicSpiderArticleSearchRunner() {
		super();
		spiderTaskService = CommonUtil.getBean(SpiderTaskService.class);
		articleSearchService = CommonUtil.getBean(ArticleSearchService.class);
	}

	@Override
	public void postInitEntry(Entry entry) throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void runTask() {
		while (true) {
			try {
				run();
				Thread.sleep(5000);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("runTask error",e);
				taskFaild();
			}
		}
	}
	
	public void taskFaild() {
		if (tasks!=null) {
			if (tasks.getRetryTimes() < RETRY_TIMES) {//重试次数小于3
				switch (tasks.getStatus()) {
				case 9://抓取链接的任务正在执行
					tasks.setStatus(0);//重置任务
					break;
				case 10://抓取内容的任务正在执行
					tasks.setStatus(2);//
					break;
				default:
					tasks.setStatus(0);//重置任务
					break;
				}
				
				tasks.setRetryTimes(tasks.getRetryTimes()+1);
			}else {
				tasks.setStatus(-1);//状态设成 -1 表示失败
			}
			try {
				spiderTaskService.updateStatus(tasks);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	/**
	 * 根据act处理不同的task
	 * @param task
	 * @return
	 * @throws Exception 
	 */
	protected SpiderTask getFormatTask(SpiderTask task) throws Exception{
		String charset = "utf-8";//url默认编码方式
		String keyword = StringUtil.getDealBaiduKeyWord(task.getKeyword());//关键字默认处理方式
		switch (task.getAct()) {
		case "baiduNews":// 百度新闻
			task.setKeyword(URLEncoder.encode(keyword, charset));
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date stdate = formatter.parse(task.getBeginTime() + " 00:00:00");
			Date etdate = formatter.parse(task.getEndTime() + " 23:59:59");
			task.setBeginTime(stdate.getTime() / 1000 + "");
			task.setEndTime(etdate.getTime() / 1000 + "");
			if(task.getSite()==null){
				task.setSite("");
			}
			break;
		case "baiduSearch":// 百度搜索
			task.setKeyword(URLEncoder.encode(keyword, charset));
			SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date stdate2 = formatter2.parse(task.getBeginTime() + " 00:00:00");
			Date etdate2 = formatter2.parse(task.getEndTime() + " 23:59:59");
			task.setBeginTime(stdate2.getTime() / 1000 + "");
			task.setEndTime(etdate2.getTime() / 1000 + "");
			if(task.getSite()==null){
				task.setSite("");
			}
			break;
		case "googleNews":// 谷歌新闻
			keyword = StringUtil.getDealGoogleKeyWord(task.getKeyword());
			task.setKeyword(URLEncoder.encode(keyword, charset));
			task.setBeginTime(DateUtil.getTruncateDateTime2(task.getBeginTime()));
			task.setEndTime(DateUtil.getTruncateDateTime2(task.getEndTime()));
			if(task.getSite()==null){
				task.setSite("");
			}else{
				task.setSite("site:"+task.getSite());
			}
			break;
		case"sogouNews":// 搜狗新闻
			charset = "gb2312";
			task.setKeyword(URLEncoder.encode(keyword, charset));
			if(task.getSite()==null){
				task.setSite("");
			}else{
				task.setSite("site:"+task.getSite());
			}
		case "sogouSearch"://搜狗搜索
			charset = "gb2312";
			task.setKeyword(URLEncoder.encode(keyword, charset));
			if(task.getSite()==null){
				task.setSite("");
			}else{
				task.setSite("site:"+task.getSite());
			}
			break;
		case "sogouZhihu":
			task.setKeyword(URLEncoder.encode(keyword, charset));
			break;
		case "xiaohongshu":
			task.setKeyword(URLEncoder.encode(keyword, charset));
			break;
		case "tiebaSearch":
			task.setKeyword(URLEncoder.encode(keyword, charset));
			break;
		default:
			task.setKeyword(URLEncoder.encode(keyword, charset));
			break;
		}
		return task;
	}
}
